package com.seewo.dubbo.debugger.admin.aop.express;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;

/**
 * Spel express上下文
 *
 * @author chenliangliang
 * @date 2018/8/1
 */
@Component
public class DebugExpressContext implements ApplicationContextAware {

    private ParserContext parserContext = new TemplateParserContext("@{", "}");
    private ExpressionParser parser = new SpelExpressionParser();
    private MyEvaluationContext context = new MyEvaluationContext();

    public void addVariable(String name, Object variable) {
        context.setVariable(name, variable);
    }

    public void removeVariable(String name) {
        context.removeVariable(name);
    }

    public Object parseSpel(String spel) {
        Expression expression = parser.parseExpression(spel, parserContext);
        return expression.getValue(context);
    }


    public <T> T parseSpel(String spel, Class<T> resultType) {
        Expression expression = parser.parseExpression(spel, parserContext);
        return expression.getValue(context, resultType);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context.setBeanResolver(new BeanFactoryResolver(applicationContext));
    }
}
